package com.example.demo.config.artemis;

import com.example.demo.mq.service.MessagingService;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.Date;

@Component
public class ActiveMqCommandRunner implements CommandLineRunner {

    @Autowired
    private MessagingService messagingService;

    @Override
    public void run(String... args) throws Exception {
        //ActiveMqManager.startServer();

        ///messagingService.sendMailMessage();



        for(int j = 0; j < 0; j++) {
            Thread.sleep(10);
            final ClientSession session = ActiveMqManager.createClientSession(ActiveMqManager.PROTO_VM, Boolean.TRUE);
            ActiveMqManager.createQueue(session, ActiveMqManager.RDO_QUEUE_VM + j);
            ClientProducer producer = ActiveMqManager.createNewProducer(session, ActiveMqManager.RDO_QUEUE_VM+ j);
            new Thread(()-> {
                for(int i = 0; i < 10000; i++) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                    }
                    ActiveMqManager.sendMessage(session, producer,Thread.currentThread().getName()  + "-" + i + ":" + new Date(), true);
                }

                ActiveMqManager.closeSession(session);
            }, "PRODUCER-" + j).start();

        }

        for(int j = 0; j < 0; j++) {
            Thread.sleep(10);
            final ClientSession session = ActiveMqManager.createClientSession(ActiveMqManager.PROTO_VM, Boolean.TRUE);
            ActiveMqManager.createQueue(session, ActiveMqManager.RDO_QUEUE_VM + j);
            ClientConsumer consumer = ActiveMqManager.createNewConsumer(session, ActiveMqManager.RDO_QUEUE_VM+ j);
            new Thread(() -> {
                for (int i = 0; i < 10000; i++) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                    }
                    String msg = ActiveMqManager.getMessage(consumer);
                    System.out.println(Thread.currentThread().getName()  + "-" + i + "->" + msg);
                }
                ActiveMqManager.closeSession(session);
            }, "CONSUMER-" + j).start();
        }
    }

    //@PreDestroy
    public void destroy() {
        ActiveMqManager.stopServer();
    }


}
